// pages/post/post-detail/post-detail.js
import { DBPost } from '../../../db/DBPost.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // post:[]
    isPlayingMusic:false
  },

  /**
   * 监听音乐播放
   */
  setMusicMonitor:function() {
    var that = this 
    wx.onBackgroundAudioStop(function (){
      that.setData({
        isPlayingMusic:false
      })
    })

  },
  /**
   * 切换播放图标
   */
  onMusicTap:function(event) {
    if (this.data.isPlayingMusic){
      wx.pauseBackgroundAudio();
      this.setData({
        isPlayingMusic:false
      })
    } else {
      wx.playBackgroundAudio({
        dataUrl: this.postData.music.url,
        title: this.postData.music.title,
        coverImgUrl:this.postData.music.coverImg,
        success:function(res) {
          console.log(res)
        },
        fail:function(res) {
          console.log(res)
        }
      })
      this.setData({
        isPlayingMusic: true
      })
    }
    // this.setData({
    //   isPlayingMusic: !this.data.isPlayingMusic
    // })

  },

  /**
   * 阅读量+1
   */
  addReadingTimes:function() {
    
    this.dbPost.addReadingTimes()
  },
  /**
   * 收藏
   */
  onCollectionTap:function(){
    var newData = this.dbPost.collect()
    this.setData({
      'post.collectionStatus':newData.collectionStatus,
      'post.collectionNum':newData.collectionNum,
    })
    wx.showToast({
      title: newData.collectionStatus?"收藏成功":"取消成功",
      duration:1000,
      icon:"success",
      mask:true
    })

  },
  /**
   * 点赞
   */
  onUpTap:function(){
    var newData = this.dbPost.up()
    console.log(newData)
    this.setData({
      'post.upNum': newData.upNum,
      'post.upStatus': newData.upStatus
    })
    wx.showToast({
      title: newData.collectionStatus?"点赞成功":"取消点赞",
      duration: 1000,
      icon: "success",
      mask: true
    })
  },
  /**
   * 评论
   */
  onCommentTap:function(event){
      var id = event.currentTarget.dataset.postId
      wx.navigateTo({
        url: '../post-comment/post-comment?id='+id,
      })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    var postId = options.id
    this.dbPost = new DBPost(postId)
    this.postData = this.dbPost.getPostItemById().data
    this.setData({
      post:this.postData,
    })
    this.addReadingTimes()
    this.setMusicMonitor()


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.setNavigationBarTitle({
      title: this.postData.title,
    })
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.pauseBackgroundAudio()
    this.setData({
      isPlayingMusic:false
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})